package com.gridmobi.xrtb.model.rtb;

import com.alibaba.fastjson.JSONObject;
import com.gridmobi.xrtb.common.URIEncoder;
import com.gridmobi.xrtb.domain.dsp.DspTrackLog;
import com.gridmobi.xrtb.domain.dsp.common.enums.CreativeTypeE;
import com.gridmobi.xrtb.model.openrtb23.Bid;
import com.gridmobi.xrtb.model.openrtb23.Imp;
import com.gridmobi.xrtb.model.openrtb23.OpenRTB23BidRequest;
import com.gridmobi.xrtb.util.ChannelHelper;
import com.gridmobi.xrtb.util.RtbUtil;
import org.apache.commons.lang3.StringUtils;

import java.net.URLDecoder;
import java.net.URLEncoder;

public class MacrosTemplate {
    public static String replaceMacros(String channel, String url, OpenRTB23BidRequest bidRequest, Campaign winCampaign, Imp imp, Bid bid) {
        if (StringUtils.isBlank(url)) {
            return "";
        }
        if (url.indexOf("{REQ_ID}") > -1) {
            url = StringUtils.replaceAll(url, "\\{REQ_ID}", bidRequest.getId());
        }

  /*      String clickid = "dsp".concat(bidRequest.getId());
        if (bidRequest.getDspTrackLog() != null) {

            bidRequest.getDspTrackLog().setClickid(clickid);
        }

        if (url.indexOf("{CLICK_ID}") > -1) {
            url = StringUtils.replaceAll(url, "\\{CLICK_ID}", clickid);
        }*/
        if (url.indexOf("{GEO}") > -1) {
            url = StringUtils.replaceAll(url, "\\{GEO}", RtbUtil.get23Country(bidRequest));
        }
        String appid = "";
        String siteId = "";
        String publisher = "";
        String appBundle = "";
        String appName = "";
        String appDomain = "";
        String siteDomain = "";
        String deviceModel = "";
        String carrier = "";
        String idfa = "";
        String os = "";
        String osv = "";
        String city = "";
        String ip = "";
        String lat = "";
        String lon = "";
        String storeurl = "";
        String ua = "";
        String[] iabs = {};
        if (bidRequest.getApp() != null) {

            if (bidRequest.getApp() != null) {
                if (bidRequest.getApp().getPublisher() != null) {
                    publisher = bidRequest.getApp().getPublisher().getId();
                }
                appName = bidRequest.getApp().getName();
                appBundle = bidRequest.getApp().getBundle();
                appDomain = bidRequest.getApp().getDomain();
                if (bidRequest.getApp().getStoreurl() != null) {
                    storeurl = URIEncoder.encodeURI(bidRequest.getApp().getStoreurl());
                }
                iabs = bidRequest.getApp().getCat();
            }
        }
        appid = RtbUtil.get23App(bidRequest);


        if (bidRequest.getSite() != null) {
            siteId = bidRequest.getSite().getId();
            siteDomain = bidRequest.getSite().getDomain();
        }

        if (bidRequest.getDevice() != null) {
            idfa = RtbUtil.get23Ifa(bidRequest);
            os = RtbUtil.get23OS(bidRequest);
            osv = bidRequest.getDevice().getOsv() == null ? "" : bidRequest.getDevice().getOsv();
            deviceModel = bidRequest.getDevice().getModel() == null ? "" : bidRequest.getDevice().getModel();
            carrier = bidRequest.getDevice().getCarrier() == null ? "" : bidRequest.getDevice().getCarrier();
            ip = bidRequest.getDevice().getIp();
            if (bidRequest.getDevice().getUa() != null) {
                ua = bidRequest.getDevice().getUa();
            }
            if (bidRequest.getDevice().getGeo() != null) {
                lat = bidRequest.getDevice().getGeo().getLat() + "";
                lon = bidRequest.getDevice().getGeo().getLon() + "";
                city = bidRequest.getDevice().getGeo().getCity();
                if (city != null) {
                    city = StringUtils.deleteWhitespace(city);
                }
            }
        }

        if (url.indexOf("{PRICE}") > -1) {
            url = StringUtils.replaceAll(url, "\\{PRICE}", winCampaign.getBidPrice()+"");
        }
        if (url.indexOf("{IDFA}") > -1) {

            url = StringUtils.replaceAll(url, "\\{IDFA}", idfa);
        }

        if (url.indexOf("{TIMESTAMP}") > -1) {

            url = StringUtils.replaceAll(url, "\\{TIMESTAMP}", System.currentTimeMillis() / 1000 + "");
        }

        if (url.indexOf("{DOMAIN}") > -1) {

            url = StringUtils.replaceAll(url, "\\{DOMAIN}", StringUtils.isEmpty(appDomain) ? siteDomain : appDomain);
        }
        if (url.indexOf("{IP}") > -1) {

            url = StringUtils.replaceAll(url, "\\{IP}", ip);
        }
     /*   if (url.indexOf("{ADVERTISING_ID}") > -1) {

            url = StringUtils.replaceAll(url, "\\{ADVERTISING_ID}", idfa);
        }
        if (url.indexOf("{ADVERTISING_ID_MD5}") > -1) {
            url = StringUtils.replaceAll(url, "\\{ADVERTISING_ID_MD5}", MD5Encoder.encode(idfa.getBytes()));
        }
        if (url.indexOf("{IDFA_MD5}") > -1) {
            url = StringUtils.replaceAll(url, "\\{IDFA_MD5}", MD5Encoder.encode(idfa.getBytes()));
        }*/
        if (url.indexOf("{DEVICE_OS}") > -1) {
            url = StringUtils.replaceAll(url, "\\{DEVICE_OS}", os);
        }
        if (url.indexOf("{DEVICE_OSV}") > -1) {
            url = StringUtils.replaceAll(url, "\\{DEVICE_OSV}", osv);
        }
        if (url.indexOf("{DEVICE_MODEL}") > -1) {
            url = StringUtils.replaceAll(url, "\\{DEVICE_MODEL}", RtbUtil.urlEncode(deviceModel));
        }
        if (url.indexOf("{CARRIER}") > -1) {
            url = StringUtils.replaceAll(url, "\\{CARRIER}", RtbUtil.urlEncode(carrier));
        }
        if (url.indexOf("{LAT}") > -1) {
            url = StringUtils.replaceAll(url, "\\{LAT}", lat);
        }
        if (url.indexOf("{CREATIVE_ID}") > -1) {
            if (winCampaign.getCreativeType() != null && (CreativeTypeE.NATIVE.code == winCampaign.getCreativeType())) {

                boolean chnAlg = ChannelHelper.isChnAlg(channel, bidRequest);
                if (chnAlg) {
                    url = StringUtils.replaceAll(url, "\\{CREATIVE_ID}", winCampaign.getNativeAdWrapper().getCreativeId()+"");
                }
                else {
                    url = StringUtils.replaceAll(url, "\\{CREATIVE_ID}", winCampaign.getCreativeNative().getId().toString());
                }

            } else {
                url = StringUtils.replaceAll(url, "\\{CREATIVE_ID}", winCampaign.getCreative().getId().toString());

            }

        }
        if (url.indexOf("{CAMPAIGN_ID}") > -1) {

            url = StringUtils.replaceAll(url, "\\{CAMPAIGN_ID}", winCampaign.getId().toString());
        }
        if (url.indexOf("{PUBLISHER_ID}") > -1) {

            url = StringUtils.replaceAll(url, "\\{PUBLISHER_ID}", publisher);
        }
        if (url.indexOf("{APP_ID}") > -1) {

            url = StringUtils.replaceAll(url, "\\{APP_ID}", appid);
        }
        if (url.indexOf("{APP_NAME}") > -1) {

            url = StringUtils.replaceAll(url, "\\{APP_NAME}", appName);
        }

        if (url.indexOf("{SITE_ID}") > -1) {

            url = StringUtils.replaceAll(url, "\\{SITE_ID}", siteId);
        }

        if (url.indexOf("{LON}") > -1) {

            url = StringUtils.replaceAll(url, "\\{LON}", lon);
        }

        if (url.indexOf("{APPNBUNDLE}") > -1) {

            url = StringUtils.replaceAll(url, "\\{APPNBUNDLE}", appBundle);
        }

        if (url.indexOf("{URL_ENCODED_APP_STORE_URL}") > -1) {

            url = StringUtils.replaceAll(url, "\\{URL_ENCODED_APP_STORE_URL}", storeurl);
        }
        if (url.indexOf("{CATEGORIES}") > -1) {

            url = StringUtils.replaceAll(url, "\\{CATEGORIES}", iabs.toString());
        }
        if (url.indexOf("{EXCHANGE}") > -1) {

            url = StringUtils.replaceAll(url, "\\{EXCHANGE}", channel);
        }

        if (url.indexOf("{EXCHANGE}") == -1 && url.indexOf("channel") == -1) {

            url = url + "&channel=" + channel;
        }

        if (url.indexOf("{IMPID}") > -1) {

            url = StringUtils.replaceAll(url, "\\{IMPID}", imp.getId());
        }
        if (url.indexOf("{CITY}") > -1) {

            url = StringUtils.replaceAll(url, "\\{CITY}", RtbUtil.urlEncode(city));
        }

        if (url.indexOf("{URL_ENCODED_USER_AGENT}") > -1) {

            url = StringUtils.replaceAll(url, "\\{URL_ENCODED_USER_AGENT}", RtbUtil.urlEncode(ua));
        }

        if (url.indexOf("{BIDID}") > -1) {

            url = StringUtils.replaceAll(url, "\\{BIDID}", bid.getId());
        }


        return url;
    }

    public static void main(String[] args) throws Exception {

        String json = "{\"allimps\":0,\"" +
                "app\":{\"bundle\":\"591560124\",\"" +
                "cat\":[\"IAB1\"],\"id\":\"120150650\",\"" +
                "name\":\"Musi_iOS-5_Musi_iOS-5_320x50-2_iOS_XXLARGE_320x50_IAB1\"," +
                "\"publisher\":{\"id\":\"1100004890\",\"name\":\"Musi_iOS-5_Musi_iOS-5_320x50-2_iOS_XXLARGE_320x50_IAB1\"}," +
                "\"storeurl\":\"https://itunes.apple.com/us/app/musi-simple-music-streaming/id591560124?mt=8\"}," +
                "\"at\":2," +
                "\"bcat\":[\"IAB17-18\",\"IAB7-42\",\"IAB23\",\"IAB7-28\",\"IAB26\",\"IAB25\",\"IAB9-9\",\"IAB24\"]," +
                "\"device\":{" +
                "\"carrier\":\"AT&T Mobility\"," +
                "\"connectiontype\":2," +
                "\"devicetype\":1," +
                "\"dnt\":0,\"" +
                "geo\":{" +
                "\"country\":\"ABW\"," +
                "\"lat\":0,\"lon\":0," +
                "\"type\":0,\"utcoffset\":0},\"h\":0," +
                "\"ip\":\"107.77.210.82\",\"js\":1,\"language\":\"en\",\"lmt\":0,\"make\":\"Apple\"," +
                "\"model\":\"iPhone 6s Plus\"," +
                "\"os\":\"iOS\",\"osv\":\"11.2\",\"ppi\":0,\"pxratio\":0,\"ua\":\"Mozilla/5.0 (iPhone; CPU iPhone OS 11_2_2 like Mac OS X) AppleWebKit/604.4.7 (KHTML, like Gecko) Mobile/15C202\",\"w\":0},\"ext\":" +
                "{\"carriername\":\"AT&T Mobility\"," +
                "\"operaminibrowser\":0," +
                "\"udi\":{\"googlednt\":0," +
                "\"idfatracking\":1}}," +
                "\"id\":\"db7283d0-d769-45a4-890c-b384d274972e\"," +
                "\"imp\":[{\"banner\":{\"api\":[3,5]," +
                "\"battr\":[1,3,5,8,9],\"btype\":[1]," +
                "\"format\":[{\"h\":50,\"w\":320}]," +
                "\"h\":50,\"hmax\":0,\"hmin\":0,\"mimes\":[\"text/javascript\",\"application/javascript\",\"image/jpeg\",\"image/png\",\"image/gif\"],\"pos\":1,\"topframe\":0,\"w\":320,\"wmax\":0,\"wmin\":0}," +
                "\"bidfloor\":0," +
                "\"bidfloorcur\":\"USD\",\"displaymanager\":\"SOMA\",\"ext\":{\"strictbannersize\":0},\"id\":\"1\",\"instl\":0,\"secure\":0,\"tagid\":\"130446559\"}],\"regs\":{\"coppa\":0,\"ext\":{\"gdpr\":0}},\"test\":0,\"tmax\":449,\"user\":{\"ext\":{},\"id\":\"822a8c76-b5ee-4577-9c0f-407a9579bafb\",\"yob\":1998}}";
        OpenRTB23BidRequest request = JSONObject.parseObject(json, OpenRTB23BidRequest.class);
        Creative c = new Creative();
        c.setId("1");
        Campaign cc = new Campaign();
        cc.setId(2L);
        cc.setCreative(c);
        String s = "http://smaato.jinglemobi.com/dspclick?channel=smaato&cid=10&crid=1-25&reqid=0322e2c7-ef5e-4713-806f-d530888791e7&appid=120109760&siteid=&domain=&appbundle=1274972321&pubid=1100033371&devid={IDFA}&devmodel=iPhone7Plus&geo=SAU&os=1&impid=1&stmp=1546846236";
        System.out.println(replaceMacros("smaato", s, request, cc, null, null));
        String cs = URLEncoder.encode("iphone pluse", "UTF-8");
        System.out.println("iphone pluse");
        System.out.println(cs);
        System.out.println(URLDecoder.decode(cs));

    }


    public static String replaceTrackurl(String trackurl, DspTrackLog trackArgs, String clickId) {


        if (StringUtils.isNotBlank(trackurl) && trackurl.indexOf("{CLICK_ID}") > -1) {
            trackurl = StringUtils.replaceAll(trackurl, "\\{CLICK_ID}", clickId);
        }

        if (StringUtils.isNotBlank(trackurl) && trackurl.indexOf("{APP_ID}") > -1) {
            trackurl = StringUtils.replaceAll(trackurl, "\\{APP_ID}", trackArgs.getAppid());
        }

        if (StringUtils.isNotBlank(trackurl) && trackurl.indexOf("{click_id}") > -1) {
            trackurl = StringUtils.replaceAll(trackurl, "\\{click_id}", clickId);
        }
        if (StringUtils.isNotBlank(trackurl) && trackurl.indexOf("{device_id}") > -1) {
            trackurl = StringUtils.replaceAll(trackurl, "\\{device_id}", trackArgs.getDevid());
        }
        if (StringUtils.isNotBlank(trackurl) && trackurl.indexOf("{idfa}") > -1) {
            trackurl = StringUtils.replaceAll(trackurl, "\\{idfa}", trackArgs.getDevid());
        }
        if (StringUtils.isNotBlank(trackurl) && trackurl.indexOf("{gaid}") > -1) {
            trackurl = StringUtils.replaceAll(trackurl, "\\{gaid}", trackArgs.getDevid());
        }
        if (StringUtils.isNotBlank(trackurl) && trackurl.indexOf("{DEVICE_ID}") > -1) {
            trackurl = StringUtils.replaceAll(trackurl, "\\{DEVICE_ID}", trackArgs.getDevid());
        }
        if (StringUtils.isNotBlank(trackurl) && trackurl.indexOf("{IDFA}") > -1) {
            trackurl = StringUtils.replaceAll(trackurl, "\\{IDFA}", trackArgs.getDevid());
        }

        if (StringUtils.isNotBlank(trackurl) && trackurl.indexOf("{RANDOM_SUBID}") > -1) {
            trackurl = StringUtils.replaceAll(trackurl, "\\{RANDOM_SUBID}", trackArgs.getBidId().substring(0, 8));
        }

        return trackurl;

    }
}
